import json
import base64
import urllib

from google.appengine.ext import db
from google.appengine.api import urlfetch

import appconfig


# Tweet model
class Tweet(db.Model):
    id = db.IntegerProperty(required=True)
    time = db.DateTimeProperty()
    text = db.StringProperty()
    log_flag = db.BooleanProperty()
    log_msg = db.StringProperty()

# save tweet log
def save(tweet_id, tweet_time, tweet_text, tweet_log_flag=False, tweet_log_msg='-'):
    tweet = Tweet(id = tweet_id,
    time = tweet_time,
    text = tweet_text,
    log_flag = tweet_log_flag,
    log_msg = tweet_log_msg)
    tweet.put()

# list tweet log
def list():
    query = Tweet.all()
    return query.fetch(20)


# clear tweet log
def clear():
    q = db.GqlQuery("SELECT * FROM Tweet")
    results = q.fetch(1000)
    for result in results:
        result.delete()


# fetch tweet from twitter
def fetch():
    cfg = appconfig.get_all()
    url = cfg['twitter_url']
    if cfg['twitter_since_id'] != '0':
        url += "?since_id=" + cfg['twitter_since_id'] 
    result = urlfetch.fetch(url)
    tweets = json.loads(result.content)
    if isinstance(tweets, dict) == False:
        tweets.sort(lambda x,y: cmp(x['id'], y['id']))
    return tweets


# post tweet to minicloud
def update(text):
    # HTTP Basic Authentication
    content_str = urllib.urlencode({
        'content' : text.encode('utf-8'),
        'source' : 'twitter_mini'})

    # post text to minicloud
    cfg = appconfig.get_all()
    auth = "Basic " + base64.b64encode(cfg['minicloud_username'] + ":" + cfg['minicloud_password'])
    result = urlfetch.fetch(url=cfg['minicloud_url'],
        payload=content_str,
        method='POST',
        headers={'Authorization' : auth})
    return result

